<template>
  <div class="eleMap">
    <div id="viewDiv">
      <div class="setPoint">
        <span id="pointButton" class="action-button esri-icon-blank-map-pin esri-widget-button esri-widget esri-interactive" type="button" title="画点"></span>
        <span v-show="isPolygonButton" id="polygonButton" class="action-button esri-icon-polygon esri-widget-button esri-widget esri-interactive" type="button" title="画防控圈"></span>
      </div>
    </div>
  </div>
</template>

<script>
  import * as esriLoader from 'esri-loader';

  export default {
    name: 'pointMap',
    props:{
      point: {
        type: Array,
        default: g_centerPoint
      },
      actionType: String,
      symbolColor: {
        type: String,
        default: "#ff0000"
      },
      ringsStr: {
        type:String
      },
      isPolygonButton: {
        type: Boolean,
        default: true
      }
    },
    data () {
      return {
        view: null,
        // ptGraphic: null,
        polygonSymbol: {
          type: 'simple-fill', // autocasts as new SimpleLineSymbol()
          color: 'rgba(0,0,0,0.3)',
          style: 'solid',
          outline: {
            color: 'white',
            width: 1
          }
        },
        _geometryEngine: null,    // 包含判断
        tempGraphicsLayer: null,  // 图层
        _polygon: null,           // 图画
        _point: null,
        polygonAry: [],
      }
    },
    created (){
      esriLoader.loadCss(cssURL);
    },
    mounted () {
      this.createMap();
    },
    methods: {
      createMap () {
        // 引入依赖
        esriLoader.loadModules([
          'esri/Map',
          'esri/views/MapView',
          'esri/layers/GraphicsLayer',
          'esri/widgets/Sketch/SketchViewModel',
          "esri/geometry/geometryEngine",
          "esri/geometry/Point",
          "esri/geometry/Polygon",
          'esri/layers/TileLayer',
          "esri/Basemap",
          'esri/Graphic'
        ], {url:dojoURL}).then(([EsriMap, MapView, GraphicsLayer, SketchViewModel, geometryEngine, Point, Polygon, TileLayer, Basemap, Graphic]) => {
          let test = false;

          if(test){
            this.map = new EsriMap({
              basemap: 'streets'
            })
          }
          else {
            var layer = new TileLayer({
              url:mapServer
            })
            var customBasemap = new Basemap({
              baseLayers: [layer],
              title: 'geometries',
              id: 'geometries'
            })
            this.map = new EsriMap({
              basemap: customBasemap
            })
          }
          const self = this;


          self._geometryEngine = geometryEngine;
          let updateGraphic
          self.tempGraphicsLayer = new GraphicsLayer();
          this.map.add(self.tempGraphicsLayer, 1);
          this.view = new MapView({
            container: 'viewDiv',
            center: g_centerPoint,
            zoom: 5,
            map: this.map
          })

          let pointSymbol = {
            type: 'picture-marker', // autocasts as new PictureMarkerSymbol()
            url:  'static/img/location_point.png',
            width: '40px',
            height: '40px'
          }
          // 编辑
          if(this.actionType == 'edit'){
            let editGeometry = new Point({
              "x": self.point[0],
              "y": self.point[1],
            })
            let editGraphic = new Graphic({
              geometry: editGeometry,
              symbol: pointSymbol
            })
            self._point = editGeometry;

            // 修改中心点
            self.view.center = [self.point[0],self.point[1]];
            self.view.graphics.add(editGraphic);

            //这里只是添加到了地图上面但是颜色的数据没有拿到

            if( self.ringsStr && self.ringsStr.length > 0 ){
              let polygonDataAry = JSON.parse(self.ringsStr);
              //这里只是添加到了地图上面但是颜色的数据没有拿到

              for(let i = 0; i < polygonDataAry.length; i++){
                let geometry = new Polygon({
                  hasZ: false,
                  hasM: true,
                  rings: polygonDataAry[i].rings,
                  spatialReference: { wkid: 4326 }
                });
                let colorAry = self.colorRgb(polygonDataAry[i].style.color);
                let colorStr = 'rgba('+colorAry[0]+','+colorAry[1]+','+colorAry[2]+','+'0.3)';
                let graphic = new Graphic({
                  geometry: geometry,
                  symbol: {
                    type: 'simple-fill', // autocasts as new SimpleLineSymbol()
                    color: colorStr,
                    style: 'solid',
                    outline: {
                      color: 'white',
                      width: 1
                    }
                  },
                });
                graphic.attributes = {
                  'uid':polygonDataAry[i].uid
                };
                self.polygonAry.push(graphic);
                self.tempGraphicsLayer.add(graphic);
              }

            }

          }

          this.view.when(function (evt) {
            let sketchViewModel = new SketchViewModel({
              view: self.view,
              layer: self.tempGraphicsLayer,
              pointSymbol: {
                type: "simple-marker", // autocasts as new SimpleMarkerSymbol()
                style: "circle",
                color: "blue",
                size: "8px", // pixels
                outline: { // autocasts as new SimpleLineSymbol()
                  color: [ 255, 255, 0],
                  width: 3 // points
                }
              },
            })
            setUpClickHandler()
            sketchViewModel.on('draw-complete', addGraphic)
            sketchViewModel.on('update-complete', addGraphic)
            sketchViewModel.on('update-cancel', addGraphic)
            let drawPointButton = document.getElementById('pointButton')
            let drawPolygonButton = document.getElementById('polygonButton')
            clickButton(drawPointButton, 'point')
            clickButton(drawPolygonButton, 'polygon')

            function clickButton (button, type) {
              button.onclick = function () {
                // 点击添加防控圈
                sketchViewModel.reset()
                if(type === 'point'){
                  // 如果有防控圈
                  if (self.tempGraphicsLayer.graphics.items && self.tempGraphicsLayer.graphics.items.length > 0) {
                    let isRemove = confirm("重置点位将删除所有防控圈，请确认是否删除？");
                    if(isRemove){
                      // 清空地图数据
                      self.view.graphics.removeAll();
                      self.tempGraphicsLayer.removeAll();
                      self.polygonAry = [];
                      self.$emit('removeAll')
                    } else {
                      return
                    }
                  } else {
                    // 清空地图数据
                    self.view.graphics.removeAll();
                    self.tempGraphicsLayer.removeAll();
                    self.polygonAry = [];
                  }
                }
                  sketchViewModel.create(type);
              }
            }
            function setActiveButton (selectedButton) {
              // focus the view to activete keyboard shortcuts for sketching
              self.view.focus()
              let elements = document.getElementsByClassName('active')
              for (let i = 0; i < elements.length; i++) {
                elements[i].classList.remove('active')
              }
              if (selectedButton) {
                selectedButton.classList.add('active')
              }
            }
            function setUpClickHandler () {
              self.view.on('click', function (evt) {
                /*self.view.hitTest(evt).then(function (response) {
                  let results = response.results
                  if (results.length && results[results.length - 1].graphic) {
                    if (!updateGraphic) {
                      updateGraphic = results[results.length - 1].graphic
                      self.tempGraphicsLayer.remove(updateGraphic)
                      sketchViewModel.update(updateGraphic.geometry)
                    }
                  }
                })*/
              })
            }
          })
          function addGraphic (evt) {
            let geometry = evt.geometry
            DrawGeometry(geometry)
          };
          function DrawGeometry(geometry){
            let symbol
            if (geometry.type === 'point') {
              symbol = pointSymbol
            }
            else if(geometry.type === 'polygon'){
              symbol = self.polygonSymbol;
              self._polygon = new Polygon(geometry);
            }
            let graphic = new Graphic({
              geometry: geometry,
              symbol: symbol
            });
            // 如果是点，保存点符号，当要重新画的时候删除对应的点
            if(geometry.type === 'point'){
              self._point = new Point(geometry);
              self.view.graphics.add(graphic);
              let map_x = parseFloat(geometry.x.toFixed(8));
              let map_y = parseFloat(geometry.y.toFixed(8));
              let data = [map_x, map_y];
              self.$emit('pointCoordinate', data);
            }else if(geometry.type === 'polygon'){
              // 必须先画点
              if(self._point){
                let within = self.withinFn(self._point, self._polygon);
                // //console.log(within)
                if(within){ // 包含点
                  graphic.attributes = {
                    'uid': graphic.uid
                  };
                  self.tempGraphicsLayer.add(graphic);
                  self.polygonAry.push(graphic)
                  self.$emit('polygonGraphic',graphic);
                }else {
                  self.s_alert("所画图形没有包含点，请重新画图形")
                }
              }else {
                self.s_alert("请先画点，再画图形！")
              }
            }

            var json = graphic.toJSON();
            //console.log(JSON.stringify(json));
            updateGraphic = null
          }
        })
      },
      // 修改填充颜色
      changeColor(uid,color){
        let self = this;
        let colorAry = this.colorRgb(color);
        for(let i = 0; i < self.polygonAry.length; i++){
          if(self.polygonAry[i].attributes.uid === uid){
            self.polygonAry[i].symbol.color = {r: colorAry[0], g: colorAry[1], b: colorAry[2], a: 0.3 };
          }
        }

          self.tempGraphicsLayer.removeAll();
          self.$nextTick(function(){
            for(let i = 0; i < self.polygonAry.length; i++){
              self.tempGraphicsLayer.add(self.polygonAry[i]);
            }
          })

      },
      // 是否包含
      withinFn( innerGeometry, outerGeometry){
        return this._geometryEngine.within( innerGeometry, outerGeometry );
      },
      // 删除对应的圈
      deleteRings(uid){
        let self = this;
        let items = this.tempGraphicsLayer.graphics.items;
        for(let i = 0; i < items.length; i++){
          if(items[i].attributes.uid === uid){
            this.tempGraphicsLayer.remove(items[i]);
            self.polygonAry.splice(i,1);
          }
        }
      }
    },
    watch:{
      actionType:function (val, oldVal) {
        if( val === 'edit' ){
          this.createMap();
        }
      },

      point:{
        handler(v1){
          // this.createMap();
        },
        deep: true
      },
      // ringsStr:{
      //   handler(vl){
      //     this.createMap()
      //   }
      // },
      // deep: true
    }
  }
</script>

<style scoped>
  .eleMap {
    width: 100%;
    height: 100%;
  }
  #viewDiv {
    width: 100%;
    height: 100%;
    z-index: -1;
  }
  .action-button {
    font-size: 16px;
    background-color: white;
    border: 1px solid #D3D3D3;
    color: #6e6e6e;
    height: 32px;
    width: 32px;
    text-align: center;
    box-shadow: 0 0 1px rgba(0, 0, 0, 0.3);
  }

  .action-button:hover,
  .action-button:focus {
    background: #0079c1;
    color: #e4e4e4;
  }
  .setPoint{
    position: absolute;
    top: 79px;
    left: 14px;
    z-index: 100;
  }
</style>
